package com.example.rpc.demo.utils;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;

public class ProtostuffSerializationUtil {
    private static Objenesis objenesis = new ObjenesisStd(true);

    public static <T> byte[] serialize(T obj) {
        Class<T> clazz  = (Class<T>)obj.getClass();
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
    }


    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        T instance = objenesis.newInstance(clazz);
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        ProtostuffIOUtil.mergeFrom(data,instance,schema);
        return instance;
    }
}
